package com.whately.core.database.common.config;

import com.whately.core.base.annotation.WhDatabase;
import com.whately.core.database.db.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.interceptor.TransactionAttributeSource;
import org.springframework.transaction.interceptor.TransactionInterceptor;

/**
 * 事务拦截器
 */
@Slf4j
public class SequenceTxWhatelyInterceptor extends TransactionInterceptor {
    //起个名字
    private String beanName;
    private String schema;

    public SequenceTxWhatelyInterceptor(String beanName, TransactionManager ptm, TransactionAttributeSource tas, String schema) {
        this.beanName = beanName;
        super.setTransactionManager(ptm);
        super.setTransactionAttributeSource(tas);
        this.schema = schema;
    }

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        log.debug("enter tx interceptor ,name {},schema {}",beanName,schema);
        String oldDs = DynamicDataSourceContextHolder.get();
        try{
            //是不是blank ，都有指定，如果是blank，则指定为默认库
            DynamicDataSourceContextHolder.set(schema);

            WhDatabase whDatabase = invocation.getMethod().getAnnotation(WhDatabase.class);

            if(whDatabase!=null){
                //关闭事务,直接进行方法调用，不开启事务
                if(whDatabase.closeTx()){
                    return invocation.proceed();
                }

                //是否设定数据源
                String dbName = whDatabase.dbName();
                if(StringUtils.isBlank(dbName)){
                    DynamicDataSourceContextHolder.set(dbName);
                }
            }

            //开启事务
            return super.invoke(invocation);
        }finally {
            DynamicDataSourceContextHolder.set(oldDs);
        }

    }

}
